﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySQLDriverCS;
using ADRoot;
using System.Threading;
using System.Diagnostics;
using System.IO;
namespace ADRoot
{
    public partial class MainControler : Form
    {
        MySQLConnection conn = new MySQLConnection();

        public MainControler()
        {
            InitializeComponent();
            CenterToScreen();
            MaximizeBox = false;
            ShowInTaskbar = true;
            if (!ConnectDB())
            {
                MessageBox.Show("数据库连接错误", "提示");
            }
            for (int i = 0; i < tabControl1.TabCount; i++)
            {
                //Console.Out.WriteLine(i);
                PageOp(i);
            }
        }


        /// <summary>
        /// 重载窗口关闭按钮
        /// 如果把登陆窗口的owner设置为这个窗口,那么,这么窗口关掉的时候,登陆窗口也跟着关掉了.这个时候就不用
        /// 重载关闭事件了
        /// </summary>
        /// <param name="e"></param>
        protected override void OnClosing(CancelEventArgs e)
        {
            // 这里写关闭窗体要执行的代码
            if (conn.State != ConnectionState.Closed)
            {
                conn.Close();
            }

        }

        /// <summary>
        /// 连接并打开数据库
        /// </summary>
        /// <returns></returns>
        private bool ConnectDB()
        {

            string dbhost = ConfigurationManagement.getConfigByKey("dbhost");
            string dbname = ConfigurationManagement.getConfigByKey("dbname");
            string dbuser = ConfigurationManagement.getConfigByKey("dbuser");
            string dbpassword = ConfigurationManagement.getConfigByKey("dbpassword");
            try
            {
                conn = new MySQLConnection(new MySQLConnectionString(dbhost, dbname, dbuser, dbpassword).AsString);
                if (conn.State != ConnectionState.Open)
                {
                    conn.Open();
                }
                MySQLCommand commn = new MySQLCommand("set names gb2312", conn);
                commn.ExecuteNonQuery();
                conn.Close();
                return true;
            }
            catch
            {
                MessageBox.Show("连接数据库出现错误,请与管理员出现问题", "提示");
                return false;
            }
        }

        public void PageOp()
        {
            switch (this.tabControl1.SelectedIndex)
            {
                case 0:
                    this.tabpage1Fun();
                    //new Thread(new ThreadStart(tabpage1Fun)).Start();
                    break;
                case 1:
                    this.tabpage2Fun();
                    // new Thread(new ThreadStart(tabpage2Fun)).Start(); 
                    break;
                case 2:
                    this.tabpage3Fun();
                    //new Thread(new ThreadStart(tabpage3Fun)).Start();
                    break;
                case 3:
                    this.tabpage4Fun();
                    //new Thread(new ThreadStart(tabpage4Fun)).Start();
                    break;
                case 4:
                    this.tabpage5Fun();
                    //new Thread(new ThreadStart(tabpage5Fun)).Start();
                    break;
                case 5:
                    this.tabPage6Fun();
                    break;
                case 6:
                    this.tabpage7Fun();
                    break;
                case 7:
                    this.tabpage8Fun();
                    break;
            }

        }
        public void PageOp(int param)
        {
            switch (param)
            {
                case 0:
                    this.tabpage1Fun();
                    break;
                case 1:
                    this.tabpage2Fun();
                    break;
                case 2:
                    this.tabpage3Fun();
                    break;
                case 3:
                    this.tabpage4Fun();
                    break;
                case 4:
                    this.tabpage5Fun();
                    break;
                case 5:
                    this.tabpage5Fun();
                    break;
                case 6:
                    this.tabpage7Fun();
                    break;
                case 7:
                    this.tabpage8Fun();
                    break;
            }

        }

        private void tabpage1Fun()
        {

            try
            {
                if (conn.State != ConnectionState.Open)
                {
                    conn.Open();
                }
                MySQLCommand commn = new MySQLCommand("set names gb2312", conn);
                commn.ExecuteNonQuery();
                Console.Out.WriteLine("start fun1:" + conn.State);
                string sql = "select * from tbl_adhost ";
                MySQLDataAdapter mda = new MySQLDataAdapter(sql, conn);
                DataSet ds = new DataSet();
                mda.Fill(ds, "tbl_adhost");
                this.dataGridView_ad_host.DataSource = ds.Tables["tbl_adhost"];
                if (conn.State != ConnectionState.Closed)
                {
                    conn.Close();
                }
                Console.Out.WriteLine("finished fun1:" + conn.State);
            }
            catch
            {
                MessageBox.Show("异常");
            }
        }
        private void tabpage2Fun()
        {
            try
            {
                if (conn.State != ConnectionState.Open)
                {
                    conn.Open();
                }
                MySQLCommand commn = new MySQLCommand("set names gb2312", conn);
                commn.ExecuteNonQuery();
                string sql = "select * from tbl_developer ";
                MySQLDataAdapter mda = new MySQLDataAdapter(sql, conn);
                DataSet ds = new DataSet();
                mda.Fill(ds, "tbl_developer");
                this.dataGridView_developer.DataSource = ds.Tables["tbl_developer"];
                if (conn.State != ConnectionState.Closed)
                {
                    conn.Close();
                }
            }
            catch
            {
                MessageBox.Show("异常");
            }
        }
        private void tabpage3Fun()
        {
            try
            {
                if (conn.State != ConnectionState.Open)
                {
                    conn.Open();
                }
                MySQLCommand commn = new MySQLCommand("set names gb2312", conn);
                commn.ExecuteNonQuery();
                string sql = "select * from tbl_ad ";
                MySQLDataAdapter mda = new MySQLDataAdapter(sql, conn);
                DataSet ds = new DataSet();
                mda.Fill(ds, "tbl_ad");
                this.dataGridView_ad.DataSource = ds.Tables["tbl_ad"];
                if (conn.State != ConnectionState.Closed)
                {
                    conn.Close();
                }
            }
            catch
            {
                MessageBox.Show("异常");
            }
        }

        private void tabpage4Fun()
        {
            try
            {
                if (conn.State != ConnectionState.Open)
                {
                    conn.Open();
                }
                MySQLCommand commn = new MySQLCommand("set names gb2312", conn);
                commn.ExecuteNonQuery();
                string sql = "select * from tbl_application ";
                MySQLDataAdapter mda = new MySQLDataAdapter(sql, conn);
                DataSet ds = new DataSet();
                mda.Fill(ds, "tbl_application");
                Console.Out.WriteLine(ds.Tables["tbl_application"]);
                this.dataGridView_application.DataSource = ds.Tables["tbl_application"];
                if (conn.State != ConnectionState.Closed)
                {
                    conn.Close();
                }
            }catch(System.ArgumentException ex)
                {
                    MessageBox.Show(ex.Message.ToString());
                }
            catch
            {
                MessageBox.Show("异常");
            }
        }
        private void tabpage5Fun()
        {
            try
            {
                if (conn.State != ConnectionState.Open)
                {
                    conn.Open();
                }
                MySQLCommand commn = new MySQLCommand("set names gb2312", conn);
                commn.ExecuteNonQuery();
                string sql = "select * from tbl_ad_application_statistics";
                MySQLDataAdapter mda = new MySQLDataAdapter(sql, conn);
                DataSet ds = new DataSet();
                mda.Fill(ds, "tbl_ad_application_statistics");
                this.dataGridView_application_statistics.DataSource = ds.Tables["tbl_ad_application_statistics"];
                if (conn.State != ConnectionState.Closed)
                {
                    conn.Close();
                }
            }
            catch
            {
                MessageBox.Show("异常");
            }
        }
        /// <summary>
        /// 广告类型
        /// </summary>
        private void tabPage6Fun()
        {
            try
            {
                if (conn.State != ConnectionState.Open)
                {
                    conn.Open();
                }
                MySQLCommand commn = new MySQLCommand("set names gb2312", conn);
                commn.ExecuteNonQuery();
                string sql = "select * from tbl_adtype";
                MySQLDataAdapter mda = new MySQLDataAdapter(sql, conn);
                DataSet ds = new DataSet();
                mda.Fill(ds, "tbl_ad_type");
                this.dataGridView1.DataSource = ds.Tables["tbl_ad_type"];
                if (conn.State != ConnectionState.Closed)
                {
                    conn.Close();
                }
            }
            catch
            {
                MessageBox.Show("异常");
            }
        }
        /// <summary>
        /// 程序类型
        /// </summary>
        private void tabpage7Fun()
        {
            try
            {
                if (conn.State != ConnectionState.Open)
                {
                    conn.Open();
                }
                MySQLCommand commn = new MySQLCommand("set names gb2312", conn);
                commn.ExecuteNonQuery();
                string sql = "select * from tbl_apptype";
                MySQLDataAdapter mda = new MySQLDataAdapter(sql, conn);
                DataSet ds = new DataSet();
                mda.Fill(ds, "tbl_app_type");
                this.dataGridView2.DataSource = ds.Tables["tbl_app_type"];
                if (conn.State != ConnectionState.Closed)
                {
                    conn.Close();
                }
            }
            catch
            {
                MessageBox.Show("异常");
            }
        }
        /// <summary>
        /// 区域
        /// </summary>
        private void tabpage8Fun()
        {
            try
            {
                if (conn.State != ConnectionState.Open)
                {
                    conn.Open();
                }
                MySQLCommand commn = new MySQLCommand("set names gb2312", conn);
                commn.ExecuteNonQuery();
                string sql = "select * from tbl_area";
                MySQLDataAdapter mda = new MySQLDataAdapter(sql, conn);
                DataSet ds = new DataSet();
                mda.Fill(ds, "tbl_area");
                this.dataGridView3.DataSource = ds.Tables["tbl_area"];
                if (conn.State != ConnectionState.Closed)
                {
                    conn.Close();
                }
            }
            catch
            {
                MessageBox.Show("异常");
            }
        }

        private void tabControl1_MouseClick(object sender, MouseEventArgs e)
        {
            try
            {
                PageOp();
            }
            catch (Exception exp)
            {
                MessageBox.Show(exp.Message);
            }
        }

        /// <summary>
        /// 执行外部命令
        /// </summary>
        /// <param name="command">命令</param>
        /// <param name="milliseconds">延迟完成</param>
        /// <returns></returns>
        private string RunCmd(string command, int milliseconds)
        {

            Process p = new Process();
            string res = string.Empty;
            p.StartInfo.FileName = "cmd.exe";
            p.StartInfo.Arguments = "/c " + command;
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.CreateNoWindow = true;
            try
            {
                if (p.Start())       //开始进程
                {
                    if (milliseconds == 0)
                        p.WaitForExit();     //这里无限等待进程结束
                    else
                        p.WaitForExit(milliseconds);  //这里等待进程结束，等待时间为指定的毫秒     

                    res = p.StandardOutput.ReadToEnd();
                }
                MessageBox.Show("备份远程数据库成功", "恭喜");
            }
            catch
            {
                MessageBox.Show("备份数据库失败", "Sorry");
            }
            finally
            {
                if (p != null)
                    p.Close();

            }
            return res;
        }

        /// <summary>
        /// 备份数据库
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button12_Click(object sender, EventArgs e)
        {
            string dbhost = ConfigurationManagement.getConfigByKey("dbhost");
            string dbuser = ConfigurationManagement.getConfigByKey("dbuser");
            string dbpassword = ConfigurationManagement.getConfigByKey("dbpassword");
            string dbname = ConfigurationManagement.getConfigByKey("dbname");
            string backuppath = ConfigurationManagement.getConfigByKey("backupPath");
            string filename = "backup_from" + dbhost + "_at" + DateTime.Now.ToString("yyyy_MM_dd_hh_mm_ss") + "time" + ".txt";
            if (backuppath.EndsWith("\\"))
            {
                backuppath += filename;
            }
            else
            {
                backuppath += ("\\" + filename);
            }

            System.Diagnostics.ProcessStartInfo info = new ProcessStartInfo();
            info.FileName = System.IO.Path.GetFullPath(".\\") + "mysqldump.exe";
            info.Arguments = " --host 61.155.169.23 -uzsinba -p5135674715 adproject > " + Environment.CurrentDirectory + "backup\\" + filename + ".txt";
            info.Arguments = " --host " + dbhost + " -u" + dbuser + " -p" + dbpassword + " " + dbname + ">" + backuppath;
            Console.Out.WriteLine(info.FileName + " " + info.Arguments);
            RunCmd(info.FileName + info.Arguments, 3000);
        }
        /// <summary>
        /// exit
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button13_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        /// <summary>
        /// 用来处理DataError错误的函数.
        /// 这个函数主要用来处理获取的数据为空时的问题
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridView_application_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            if(this.dataGridView_application.Rows[e.RowIndex].IsNewRow)
            {
                //Console.Out.WriteLine(this.dataGridView_application.Rows[e.RowIndex].ToString());
                return;
            }
        }
    }
}
